package com.chixing.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * @author Wesley
 * @version 1.0
 * @date 2021/11/3 18:06
 */
@Component
public class PrimaryKeyUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    public  Integer getOrderId() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.MILLISECOND);
        //String.format("%1$02d", var)
        // %后的1指第一个参数，当前只有var一个可变参数，所以就是指var。
        // $后的0表示，位数不够用0补齐，如果没有这个0（如%1$nd）就以空格补齐，0后面的n表示总长度，总长度可以可以是大于9例如（%1$010d），d表示将var按十进制转字符串，长度不够的话用0或空格补齐。
        String dayFormat = String.format("%1$02d", day);
        String hourFormat = String.format("%1$02d", hour);
        String prefix = dayFormat+hourFormat;
        String key = "ORDER_ID_" + prefix;
        String orderId = null;
        try {
            Long increment = redisTemplate.opsForValue().increment(key,1);
            //往前补6位
            orderId=prefix+String.format("%1$04d",increment);
        } catch (Exception e) {
            String[] chars = new String[] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
            StringBuffer shortBuffer = new StringBuffer();
            String uuid = UUID.randomUUID().toString().replace("-","");
            for (int j=0;j<8;j++) {
                String str=uuid.substring(j*2,j*2+2);
                int par=Integer.parseInt(str,24);
                shortBuffer.append(chars[par % 10]);
            }
            orderId = shortBuffer.toString();
            e.printStackTrace();
        }
        return Integer.valueOf(orderId);
    }
}
